<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { dataPopularCategories } from '@/apis/apis.js'
import * as echarts from 'echarts/core'
import { TooltipComponent, LegendComponent } from 'echarts/components'
import { PieChart } from 'echarts/charts'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout
])

let echart = null
const data = ref([])
const echartRef = ref(null)
const echartOption = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})

const getData = async () => {
  const res = await dataPopularCategories()
  data.value = res.data
}

const resize = () => {
  if (echart) {
    echart.resize()
  }
}

onMounted(async () => {
  await getData()
  echart = echarts.init(echartRef.value)
  echart.setOption(echartOption.value)
  window.addEventListener('resize', resize)
})

onUnmounted(() => {
  if (echart) {
    echart.dispose()
  }
  window.removeEventListener('resize', resize)
})

watch(data, () => {
  echartOption.value.series[0].data = data.value
})
</script>

<template>
  <div class="container">
    <div class="title">热门分类</div>
    <div class="content">
      <div ref="echartRef" style="height: 300px;"></div>
    </div>
  </div>
</template>

<style scoped>
.container {
  .title {
    display: flex;
    align-items: center;
    height: 32px;
  }
}
</style>
